export const useRecentPlayStore = defineStore(
  "recentPlayStore",
  () => {
    const { games } = useGamesData(); // 获取 newGames 数据源

    const recentPlayGames = ref<Array<any>>([]);

    const addPlayGame = (game: any) => {
      const existingGameIndex = recentPlayGames.value.findIndex(
        (item) => item.id === game.id
      );
      if (existingGameIndex !== -1) {
        // 如果游戏已存在，先删除
        recentPlayGames.value.splice(existingGameIndex, 1);
      }
      // 添加到数组开头
      recentPlayGames.value.unshift(game);
      // 限制数组长度为 5
      if (recentPlayGames.value.length > 5) {
        recentPlayGames.value.pop();
      }
    };

    onMounted(() => {
      // 更新一下数据源 以免数据源属性更新
      const recentPlayGameIds = unref(recentPlayGames).map((game) => game.id);
      recentPlayGames.value = unref(games).filter((game) =>
        recentPlayGameIds.includes(game.id)
      );
    });

    return {
      recentPlayGames, // 提供计算属性
      addPlayGame, // 提供添加游戏的方法
    };
  },
  {
    persist: true, // 启用持久化
  }
);
